//
//  RequestManger.swift
//  LivelyChat
//
//  Created by admin on 2021/6/23.
//

import UIKit
import Alamofire

private let NetWorkRequestShareInstance = RequestManger()

class RequestManger:NSObject{
    class var sharedInstance:RequestManger {
        return NetWorkRequestShareInstance
    }
}

        
extension RequestManger{

    class func uploadImgRequest(UrlString:String,params:[String:Any]?,success:@escaping(_ response:[String:AnyObject])->(),failure:@escaping(_ error:Error)->()) {
        
        
        let headers = ["content-type":"multipart/form-data"]
        let PathUrl = BaseUrl + UrlString
        
        Alamofire.upload(multipartFormData: { (multipartforData) in
            let flag = params!["file"]
            multipartforData.append(flag as! Data, withName: "file", fileName: "avatar.jpg", mimeType: "image/jpeg")
        }, to: PathUrl,
           headers: headers,
           encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    if let value = response.result.value as? [String: AnyObject]{
                        let dict = value
                        if let dataDict = dict["data"] as? [String : Any] {
                            let jsonData = try? JSONSerialization.data(withJSONObject: dataDict, options: [])
                            if jsonData != nil {
                                success(dataDict as [String : AnyObject])
                                return
                            }
                        }
                    }
                }
            case .failure(let encodingError):
                Toast_View_Tool.dismiss()
                print(encodingError)
            }
        }
        )

    }

    
    class func uploadAudioRequest(UrlString:String,params:[String:Any]?,success:@escaping(_ response:[String:AnyObject])->(),failure:@escaping(_ error:Error)->()) {
        
        Toast_View_Tool.show()
        let headers = ["content-type":"multipart/form-data"]
        let PathUrl = BaseUrl + UrlString
        
        Alamofire.upload(multipartFormData: { (multipartforData) in
            let flag = params!["file"]
            multipartforData.append(flag as! Data, withName: "file", fileName: "audio.aac", mimeType: "aac")
        }, to: PathUrl,
           headers: headers,
           encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    if let value = response.result.value as? [String: AnyObject]{
                        let dict = value
                        if let dataDict = dict["data"] as? [String : Any] {
                            let jsonData = try? JSONSerialization.data(withJSONObject: dataDict, options: [])
                            if jsonData != nil {
                                success(dataDict as [String : AnyObject])
                                Toast_View_Tool.dismiss()
                                return
                            }
                        }
                    }
                }
                Toast_View_Tool.dismiss()
            case .failure(let encodingError):
                print(encodingError)
            }
        }
        )


    }
    class func postRequest(UrlString:String,params:[String:Any]?,success:@escaping(_ response:String)->(),failure:@escaping(_ error:Error)->()) {
        
        
        let para:[String:Any] = params!
        let PathUrl = BaseUrl + UrlString
        
        let appidStr = UserModel().getUUID()
        let screenStr = "\(screenWidth)*\(screenHeight)"
        let modelStr = UserModel().iphoneType()
        let str = "\(UserModel.getTimeCHUO())"

        let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
        var localPara:[String:Any] = ["appid":appidStr,
                                      "channel":"default","from":"ios","net":"Wifi","os":UIDevice.current.systemVersion,"model":modelStr,"screen":screenStr,"timestamp":str,"version":appVersion ?? "1.0.2","appPackage":"Xvi234"]
        for (k, v) in para {
            localPara.updateValue(v, forKey: k)
        }
        let appinfoStr = "Xvi234#".appending(appVersion ?? "1.0.2")
        let headers = ["Content-Type" : "application/json","appinfo":appinfoStr]
        
        print("localPara===-----   ")
        print(localPara)
        
        Alamofire.request(PathUrl, method: .post, parameters: localPara, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
            switch response.result{
                case .success(_):
                    
                    let dict = response.result.value as? NSDictionary
                    let resCode = dict!["code"] as? String

                Toast_View_Tool.dismiss()
                    
//                    let arr : NSArray = dict!.allKeys as NSArray
                    if resCode == "0" {
                    
                        if let value = response.result.value as? NSDictionary{
                            let dict = value as? [String:Any]
                            let dataDict = dict!["data"]
                            let jsonData = try? JSONSerialization.data(withJSONObject: dataDict, options: [])
                            let jsonStr = NSString(data: jsonData!, encoding: String.Encoding.utf8.rawValue)
                            
                            print("requestsuccess===---   ")
                            print(PathUrl)
                            print("\(dict)")
                            
                            if jsonStr != nil {
                                Toast_View_Tool.dismiss()
                                success(jsonStr! as String)
                                return
                            }
                        }
                        
                    }else
                    {
                        Toast_View_Tool.dismiss()
                        Toast_View_Tool.show(type: .error,text: dict!["msg"] as! String)
                    }
                        
                case .failure(let encodingError):
                    Toast_View_Tool.dismiss()
                    print(encodingError)
            }
        }
    }
        
}
